package com.nunbey.lingxi.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csvreader.CsvWriter;
import com.nunbey.lingxi.dao.RecordMapper;
import com.nunbey.lingxi.deep_predict.HeartPredict;
import com.nunbey.lingxi.mode.record.RecordDTO;
import com.nunbey.lingxi.mode.record.RecordEntity;
import com.nunbey.lingxi.mode.record.RecordListItem;
import com.nunbey.lingxi.mode.record.RecordVO;
import common.webresult.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class RecordService {

    @Autowired
    private RecordMapper recordMapper;

    @Transactional
    public WebResult recordAndDistinguish(RecordDTO recordDTO) throws IOException {
        System.out.println(recordDTO);
        int userId = StpUtil.getLoginIdAsInt();

        //将测试数据以csv的形式存储
        String fileName = "UID" + userId + "D" +
                LocalDateTime.now().toString().replace(':', '-').replace('.', '-') + ".csv";
        CsvWriter csvWriter = new CsvWriter(fileName, ',', StandardCharsets.UTF_8);
        String[] headers = { "rate"};
        csvWriter.writeRecord(headers);
        for(int i=0;i<recordDTO.getRates().size();i++){
            String[] rate = {Integer.toString(recordDTO.getRates().get(i))};
            csvWriter.writeRecord(rate);
        }
        csvWriter.close();
        //对心脏数据进行判别
        HeartPredict heartPredict = new HeartPredict();
        String result = heartPredict.heartPredict(recordDTO.getRates());
        //生成记录实体类并持久化
        RecordEntity recordEntity = new RecordEntity(null,userId,fileName,recordDTO.getAverageRate(),recordDTO.getHeartRiskAwareness(),recordDTO.getHeartAge(),recordDTO.getRelaxation(),recordDTO.getRespiration(),recordDTO.getHeartFitnessLevelLabel(),recordDTO.getR_r_interval(),result,null);
        recordMapper.insert(recordEntity);
        //将判别存储后的数据返回给用户
        RecordVO recordVO = new RecordVO(recordEntity.getRecordId(),recordEntity.getAverageRate(),recordEntity.getHeartRiskAwareness(),recordEntity.getHeartAge(),recordEntity.getRelaxation(),recordEntity.getRespiration(),recordEntity.getHeartFitnessLevelLabel(),recordEntity.getR_r_interval(),recordEntity.getDistinguish(),recordEntity.getRecordTime());
        return WebResult.okWebResult(recordVO);
    }

    /**
     * 通过ECG记录ID获取ECG数据
     * @param recordId
     * @return
     */
    public WebResult getRecordByRecordId(Long recordId){
        QueryWrapper<RecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ecg_record_id",recordId);
        System.out.println(recordId);
        RecordEntity recordEntity = recordMapper.selectOne(queryWrapper);
        RecordVO recordVO = new RecordVO(recordId,recordEntity.getAverageRate(),recordEntity.getHeartRiskAwareness(),recordEntity.getHeartAge(),recordEntity.getRelaxation(),recordEntity.getRespiration(),recordEntity.getHeartFitnessLevelLabel(),recordEntity.getR_r_interval(),recordEntity.getDistinguish(),recordEntity.getRecordTime());
        return WebResult.okWebResult(recordVO);
    }

    /**
     * 获取某个用户的ECG记录列表
     * @return
     */
    @Transactional
    public WebResult getUserRecordList() {
        int userId = StpUtil.getLoginIdAsInt();
        QueryWrapper<RecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<RecordEntity> recordEntities = recordMapper.selectList(queryWrapper);
        ArrayList<RecordListItem> result = new ArrayList<>();
        for(int i=0;i<recordEntities.size();i++){
            RecordListItem recordListItem = new RecordListItem(recordEntities.get(i).getRecordId(),recordEntities.get(i).getDistinguish(),recordEntities.get(i).getRecordTime().toString());
            result.add(recordListItem);
        }
        return WebResult.okWebResult(result);
    }
}
